<template>
  <div>
    <ul class="article bg-w" v-if="tag == 0">
      <template v-for="(item, i) in allData">
        <template v-if="item.username">
          <User :key="i" :item="item"></User>
        </template>
        <template v-else>
          <ArticleItem
            :key="i"
            :article="item"
            :i="i"
            @addAgree="addAgree"
          ></ArticleItem>
        </template>
      </template>
    </ul>
    <ul class="article bg-w" v-if="tag == 1">
      <ArticleItem
        v-for="(item, i) in data"
        :key="i"
        :article="item"
        :i="i"
        @addAgree="addAgree"
      ></ArticleItem>
    </ul>
    <ul class="user bg-w" v-else-if="tag == 2">
      <User v-for="(item, i) in users" :key="i" :item="item"></User>
    </ul>
  </div>
</template>

<script>
import User from "@/components/search/main/User";
import ArticleItem from "@/components/main/MainComponents/article/ArticleItem";
import { searchFromArticle, searchFromUser, searchFromAll } from "@/api";
import {
  normlizeArticleMsgAndAddColor,
  getSessionStorage,
  normliszeUser,
  normliszeAll,
} from "@/utils/utils";
export default {
  name: "Content",
  components: {
    User,
    ArticleItem,
  },
  data() {
    return {
      data: [],
      tag: 1,
      users: [],
      allData: [],
    };
  },
  methods: {
    addAgree(obj) {
      this.data[obj.key].agree += obj.num;
    },
    getSearchMsg() {
      const q = location.search.slice(3);
      const tag = getSessionStorage("tag");
      return {
        q,
        tag,
      };
    },
    // 获取搜索文章
    async getArticle(q) {
      const r = await searchFromArticle(q);
      this.data = normlizeArticleMsgAndAddColor(r.data, q);
    },
    // 获取搜索的用户
    async getUser(q) {
      const r = await searchFromUser(q);
      this.users = normliszeUser(r.data, q);
    },
    async getAll(q) {
      const r = await searchFromAll(q);
      this.allData = normliszeAll(r.data, q);
    },
  },
  async created() {
    // 默认加载一次
    const { q, tag } = this.getSearchMsg();
    this.tag = tag;
    if (q && q !== this.value) {
      if (tag == 0) {
        this.getAll(q);
      } else if (tag == 1) {
        this.getArticle(q);
      } else if (tag == 2) {
        this.getUser(q);
      }
    }

    this.$bus.$on("getNewSeachContent", async () => {
      const { tag, q } = this.getSearchMsg();
      this.tag = tag;
      if (q && q !== 0) {
        // tag: 1为文章 2为用户
        if (tag == 0) {
          this.getAll(q);
        } else if (tag == 1) {
          // 文章
          this.getArticle(q);
        } else if (tag == 2) {
          // 搜索用户
          this.getUser(q);
        }
      }
    });
  },
};
</script>

<style lang="scss" scoped>
.no-found {
  padding: 3rem;
  text-align: center;
}
</style>